package org.feiye.studyday28.case3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

//客户端
public class LoginClient2 {
	public static void main(String[] args) {
		Socket socket = null;
		OutputStream os = null;
		ObjectOutputStream oos = null;
		InputStream is = null;
		BufferedReader br = null;
		try {
			// 发送请求到服务器
			// 创建客户端的Socket
			socket = new Socket("localhost", 5000);
			// 通过输出流发送请求：
			User user = new User("tom", "123456");
			os = socket.getOutputStream();
			oos = new ObjectOutputStream(os);
			oos.writeObject(user);
			socket.shutdownOutput();
			// 接收服务器的响应
			is = socket.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			String reply;
			while ((reply = br.readLine()) != null) {
				System.out.println("服务器发出响应：" + reply);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			if (br != null)
				try {
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (oos != null)
				try {
					oos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			if (os != null)
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}
